<template>
  <el-container style="padding: 20px">
    <el-header style="margin-bottom: 20px; font-size: 24px">任务尝试记录</el-header>

    <!-- 搜索区域 -->
    <el-card shadow="always" style="margin-bottom: 20px">
      <el-form :inline="true" :model="searchForm" label-width="80px">
        <el-form-item label="任务名称">
          <el-input v-model="searchForm.title" placeholder="输入任务名关键字" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="输入用户名关键字" />
        </el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form>
    </el-card>

    <!-- 表格展示 -->
    <el-card shadow="always">
      <el-table :data="displayAttempts" style="width: 100%">
        <el-table-column prop="title" label="任务标题"></el-table-column>
        <el-table-column prop="description" label="任务描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="username" label="用户名称"></el-table-column>
        <el-table-column prop="startTime" label="开始时间">
          <template #default="{ row }">
            {{ formatLocalDateTimeArray(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间">
          <template #default="{ row }">
            {{ formatLocalDateTimeArray(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分">
          <template #default="{ row }">
            <el-tag :type="row.score >= 60 ? 'success' : 'danger'">{{ row.score }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button link size="small" @click="showDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹窗详情 -->
    <el-dialog v-model="detailVisible" title="任务尝试详情" width="70%">
      <div v-if="selectedAttempt">
        <h3>任务：{{ selectedAttempt.title }}</h3>
        <p>{{ selectedAttempt.description }}</p>

        <h3 style="margin-top: 20px">步骤完成情况</h3>
        <el-table :data="selectedSteps" border>
          <el-table-column prop="title" label="步骤标题"></el-table-column>
          <el-table-column prop="description" label="内容" show-overflow-tooltip></el-table-column>
          <el-table-column prop="maxScore" label="总分"></el-table-column>
          <el-table-column prop="score" label="得分"></el-table-column>
          <el-table-column prop="createdAt" label="完成时间">
            <template #default="{ row }">
              {{ formatLocalDateTimeArray(row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from '@/utils/axios'
import {useUserStore} from "@store/userStore.js";
import {formatLocalDateTimeArray} from "@/utils/utils"
const userStore = useUserStore()
const isStudent = ref(userStore.role === 'student')

// 请求数据
const allAttempts = ref([])
const displayAttempts = ref([])
const stepsMap = ref({}) // missionAttemptId -> steps[]
const searchForm = ref({
  title: '',
  username: ''
})
const detailVisible = ref(false)
const selectedAttempt = ref(null)
const selectedSteps = ref([])

onMounted(async () => {
  await fetchAttempts()
})

async function fetchAttempts() {
  const res = await axios.get('/api/mission/attempts')
  allAttempts.value = res.data.map(item => ({
    ...item,
    username: item.userId // 假设后端返回了 userId，你可以扩展成真实用户名
  }))
  filterData()
}

function filterData() {
  let data = [...allAttempts.value]

  if (isStudent.value) {
    data = data.filter(a => a.userId === userStore.user.id)
  }

  if (searchForm.value.title) {
    const keyword = searchForm.value.title.toLowerCase()
    data = data.filter(a => a.title?.toLowerCase().includes(keyword))
  }

  if (searchForm.value.username) {
    const keyword = searchForm.value.username.toLowerCase()
    data = data.filter(a => a.username?.toLowerCase().includes(keyword))
  }

  displayAttempts.value = data
}

function handleSearch() {
  filterData()
}

function resetSearch() {
  searchForm.value.title = ''
  searchForm.value.username = ''
  filterData()
}

async function showDetail(attempt) {
  selectedAttempt.value = attempt
  // 如果没有缓存过步骤，就请求一次
  if (!stepsMap.value[attempt.id]) {
    try {
      const res = await axios.get(`/api/mission/stepAttempts/${attempt.id}`)
      stepsMap.value[attempt.id] = res.data || []
    } catch (e) {
      stepsMap.value[attempt.id] = []
    }
  }
  selectedSteps.value = stepsMap.value[attempt.id]
  detailVisible.value = true
}
</script>
